package com.xiashitech.agent.instrumentation.tomcat.valve.standardengine.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.instrumentation.base.context.ReentryContextStorage;
import com.xiashitech.agent.instrumentation.base.propagator.W3CReentryBaggagePropagator;
import com.xiashitech.agent.instrumentation.bridge.Java8Bridge;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSStandardEngineValveCallDepth;
import com.xiashitech.agent.instrumentation.tomcat.common.TomcatResponseSetter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import net.bytebuddy.asm.Advice;
import org.apache.catalina.connector.Response;

@SuppressWarnings("unused")
public class XSStandardEngineValveAdvice {

  @Advice.OnMethodEnter(suppress = Throwable.class)
  public static void startSpan(
          @Advice.Local("otelCallDepth") CallDepth callDepth) {
    if(CacheStatus.cannotRun()) {
      return;
    }
    callDepth = CallDepth.forClass(XSStandardEngineValveCallDepth.class);
    if (callDepth.getAndIncrement() > 0) {
      return;
    }
  }

  @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
  public static void stopSpan(
      @Advice.Argument(value = 1) Response response,
      @Advice.Local("otelCallDepth") CallDepth callDepth) {
    if(CacheStatus.cannotRun()) {
      return;
    }
    if(callDepth.decrementAndGet() > 0) {
      return;
    }
    W3CReentryBaggagePropagator.getInstance().inject(Java8Bridge.currentForXSContext(),response,TomcatResponseSetter.INSTANCE);
    //清空response中的上下文。
    ReentryContextStorage.INSTANCE.close();
  }
}
